package com.gxb.codebook;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.viewmodel.CreationExtras;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.gxb.codebook.adapter.NotepadAdapter;
import com.gxb.codebook.bean.NotepadBean;
import com.gxb.codebook.database.SQLiteHelper;

import java.util.List;

public class ListActivity extends Fragment implements HomeActivity.DataRefreshListener {
    private ListView listView;
    private NotepadAdapter adapter;
    private List<NotepadBean> notepadList;
    private SQLiteHelper dbHelper;
    private Button notepad_btn;
    private Dialog mDialog;
    private FragmentActivity mActivity;
    private BroadcastReceiver themeChangeReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_list, container, false);
        listView = view.findViewById(R.id.listview);
        dbHelper = new SQLiteHelper(getContext());
        notepadList = dbHelper.getAllNotepads();
        mActivity = getActivity();
        notepad_btn = view.findViewById(R.id.notepad_btn);
        adapter = new NotepadAdapter(getContext(), notepadList);
        notepad_btn.setOnClickListener(v -> notepad_btn());
        listView.setAdapter(adapter);
        listView.setDivider(null);

        // 设置点击监听器
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NotepadBean notepad = notepadList.get(position);
                Intent intent = new Intent(getActivity(), RecordActivity.class);
                intent.putExtra("id", notepad.getId());
                intent.putExtra("time", notepad.getNotepadTime());
                intent.putExtra("content", notepad.getNotepadContent());
                startActivityForResult(intent, 1);

                // 发送笔记点击事件广播
                if (localBroadcastManager != null) {
                    Intent clickIntent = new Intent("NOTEPAD_ITEM_CLICKED");
                    clickIntent.putExtra("notepad_id", notepad.getId());
                    localBroadcastManager.sendBroadcast(clickIntent);
                }
            }
        });

        // 设置长按监听器
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                showDeleteDialog(position);

                // 发送笔记长按事件广播
                if (localBroadcastManager != null) {
                    Intent longClickIntent = new Intent("NOTEPAD_ITEM_LONG_CLICKED");
                    longClickIntent.putExtra("notepad_id", notepadList.get(position).getId());
                    localBroadcastManager.sendBroadcast(longClickIntent);
                }

                return true;
            }
        });

        // 初始化LocalBroadcastManager
        if (mActivity != null) {
            localBroadcastManager = LocalBroadcastManager.getInstance(mActivity);

            // 注册广播接收器
            themeChangeReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if ("THEME_CHANGED".equals(intent.getAction())) {
                        if (mActivity != null) {
                            mActivity.recreate();
                        }
                    }
                }
            };

            IntentFilter filter = new IntentFilter("THEME_CHANGED");
            localBroadcastManager.registerReceiver(themeChangeReceiver, filter);
        }

        return view;
    }

    private void showDeleteDialog(final int position) {
        mDialog = new Dialog(mActivity);
        mDialog.setContentView(R.layout.delete);
        mDialog.setCancelable(false);

        if (mDialog.getWindow() != null) {
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            int widthInDp = 300;
            int widthInPx = (int) (widthInDp * getResources().getDisplayMetrics().density);
            mDialog.getWindow().setLayout(widthInPx, WindowManager.LayoutParams.WRAP_CONTENT);
        }

        Button outbtn = mDialog.findViewById(R.id.delete_no);
        outbtn.setOnClickListener(v -> {
            mDialog.dismiss();

            // 发送取消删除事件广播
            if (localBroadcastManager != null) {
                Intent cancelIntent = new Intent("NOTEPAD_DELETE_CANCELLED");
                cancelIntent.putExtra("notepad_id", notepadList.get(position).getId());
                localBroadcastManager.sendBroadcast(cancelIntent);
            }
        });

        Button yesbtn = mDialog.findViewById(R.id.delete_yes);
        yesbtn.setOnClickListener(v -> {
            dbHelper.deleteNotepad(notepadList.get(position).getId());
            refreshData();
            mDialog.dismiss();

            // 发送笔记删除成功事件广播
            if (localBroadcastManager != null) {
                Intent deleteIntent = new Intent("NOTEPAD_DELETED");
                deleteIntent.putExtra("notepad_id", notepadList.get(position).getId());
                localBroadcastManager.sendBroadcast(deleteIntent);
            }
        });

        mDialog.show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (localBroadcastManager != null && themeChangeReceiver != null) {
            try {
                localBroadcastManager.unregisterReceiver(themeChangeReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

    private void notepad_btn() {
        Intent intent = new Intent(getActivity(), RecordActivity.class);
        startActivityForResult(intent, 1);
        refreshData();

        // 发送新建笔记事件广播
        if (localBroadcastManager != null) {
            Intent newNotepadIntent = new Intent("NEW_NOTEPAD_STARTED");
            localBroadcastManager.sendBroadcast(newNotepadIntent);
        }
    }

    @Override
    public void refreshData() {
        notepadList = dbHelper.getAllNotepads();
        adapter.updateData(notepadList);

        // 发送数据刷新事件广播
        if (localBroadcastManager != null) {
            Intent refreshIntent = new Intent("NOTEPAD_DATA_REFRESHED");
            refreshIntent.putExtra("count", notepadList.size());
            localBroadcastManager.sendBroadcast(refreshIntent);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 2) {
            refreshData();
        }
    }

    @NonNull
    @Override
    public CreationExtras getDefaultViewModelCreationExtras() {
        return super.getDefaultViewModelCreationExtras();
    }
}
